package com.study.lxy.concurrent.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class TwinsLock implements Lock {

    private final Sync sync = new Sync(2);
    private static final class Sync extends AbstractQueuedSynchronizer {

        Sync(int count) {
            if(count <= 0 ){
                throw new IllegalArgumentException("count must greater than zero");
            }
            setState(count);
        }
        @Override
        public int tryAcquireShared(int reduceCount){

            for(;;){
                int current = getState();
                int stateAfter = current - reduceCount;
                if(stateAfter < 0 || compareAndSetState(current,stateAfter)){
                    return stateAfter;
                }
            }
        }
        @Override
        public boolean tryReleaseShared(int count){
            for(;;){

                int current = getState();
                int stateAfter = current + count;
                if(compareAndSetState(current,stateAfter)){
                    return true;
                }
            }
        }
        public Condition newCondition(){
            return new ConditionObject();
        }
    }

    public void lock() {
        sync.acquireShared(1);
    }

    public void lockInterruptibly() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

    public boolean tryLock() {
        return sync.tryAcquireShared(1) >= 0;
    }

    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireSharedNanos(1,unit.toNanos(time));
    }

    public void unlock() {
        sync.releaseShared(1);
    }

    public Condition newCondition() {
        return sync.newCondition();
    }
}
